﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using Elderos.Utils.Logging;

namespace Elderos.TextSearchers
{
	public abstract class TextSearcherBase : ITextSearcher
	{
		private bool _initialized;
		private readonly object _initializationLocker = new object();

		#region Implementation of ITextSearcher

		public void Initialize(IStringLoader stringLoader, int? maxCount)
		{
			if (_initialized)
				throw new InvalidOperationException("Already initialized.");
			lock (_initializationLocker)
			{
				if (_initialized)
					throw new InvalidOperationException("Already initialized.");
				Logger.Info("Initializing TextSearcher...");

				Logger.Info("Begin LoadStrings phase...");
				foreach (string str in  stringLoader.LoadStrings(maxCount))
					ProcessString(str);
				Logger.Info("LoadStrings phase completed.");

				Logger.Info("Begin OnStringsLoaded phase...");
				OnStringsLoaded();
				Logger.Info("OnStringsLoaded phase completed.");

				_initialized = true;
				Logger.Info("TextSearcher initialized.");
			}
		}

		protected virtual void OnStringsLoaded() {}

		public IEnumerable<Position> Search(string text)
		{
			if (text == null)
				throw new ArgumentException("text");

			if (!_initialized)
				throw new InvalidOperationException("TextSearcher is not initialized");

			return InnerSearch(text);
		}

		public abstract int LoadedStringsCount { get; }

		protected abstract IEnumerable<Position> InnerSearch(string text);

		protected abstract void ProcessString(string str);

		#endregion
	}
}
